import React from "react";
import App from "next/app";
import { ViewApi } from "@/api/view";
import { SettingApi } from "@/api/setting";
import { PageApi } from "@/api/page";
import { CategoryApi } from "@/api/categroy";
import { TagApi } from "@/api/tags";
import { ClientLayout } from "@/layout";
import { NProgress } from "@components/NProgress";
import "viewerjs/dist/viewer.css";
import "highlight.js/styles/monokai-sublime.css";
import "@/theme/antd.less";
import "@/theme/reset.scss";
import "@/theme/markdown.scss";

let lastUrl;

const addView = (url) => {
  if (/localhost/.test(url)) {
    return;
  }
  ViewApi.addView({ url });
};

class MyApp extends App {
  static getInitialProps = async (ctx) => {
    const [appProps, setting, tags, categorys, pages] = await Promise.all([
      App.getInitialProps(ctx),
      SettingApi.getSettings(),
      TagApi.getAll({ articleStatus: "publish" }),
      CategoryApi.getAll({ articleStatus: "publish" }),
      PageApi.getAllPublishPage(),
    ]);
    return { ...appProps, setting, tags, categorys, pages: pages[0] || [] };
  };

  componentDidMount() {
    try {
      const el = document.querySelector("#holderStyle");
      el.parentNode.removeChild(el);
    } catch (e) {}

    const url = window.location.href;
    lastUrl = url;
    addView(url);
  }

  componentDidUpdate() {
    const url = window.location.href;
    if (url === lastUrl) {
      return;
    }
    lastUrl = url;
    addView(url);
  }

  render() {
    const {
      Component,
      pageProps,
      setting = {},
      tags = [],
      categorys = [],
      pages = [],
    } = this.props as any;
    const { needLayoutFooter = true } = pageProps;
    return (
      <ClientLayout
        setting={setting}
        pages={pages}
        needFooter={needLayoutFooter}
      >
        <style
          id="holderStyle"
          dangerouslySetInnerHTML={{
            __html: ` * {
      transition: none !important;
    }`,
          }}
        ></style>
        <NProgress color={"#ff0064"} />
        <Component
          {...pageProps}
          setting={setting}
          tags={tags}
          categorys={categorys}
          pages={pages}
        />
      </ClientLayout>
    );
  }
}

export default MyApp;
